<!-- 数据采集页 -->
<template>
  <div class="data-collection">
    <!-- 查询表单 -->
    <el-form class="demo-form-inline" ref="formRef" :model="queryForm" label-width="100px" size="small" inline>
      <el-form-item label="工单标题" prop="title">
        <el-input v-model="queryForm.title" placeholder="工单标题" clearable></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryForm.status" placeholder="请选择状态" clearable>
          <el-option label="待处理" value="待处理"></el-option>
          <el-option label="处理中" value="处理中"></el-option>
          <el-option label="已完成" value="已完成"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="fetchWorkOrders">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-refresh" @click="resetData">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <div class="el-row">
      <el-button type="info" icon="el-icon-coin" plain size="small" @click="showImportDialog">导入数据</el-button>
      <el-button type="success" icon="el-icon-plus" plain size="small" @click="handleAdd">新增工单</el-button>
    </div>

    <!-- 工单列表 -->
    <el-table
      :data="tableData"
      height="100%"
      style="width: 100%; "
      @selection-change="handleSelectionChange"
      v-loading="loading"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column type="index" label="序号" width="50"></el-table-column>
      <el-table-column prop="title" label="工单标题"></el-table-column>
      <el-table-column prop="status" label="状态">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === '待处理'" type="info">{{ scope.row.status }}</el-tag>
          <el-tag v-else-if="scope.row.status === '处理中'" type="warning">{{ scope.row.status }}</el-tag>
          <el-tag v-else type="success">{{ scope.row.status }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="assignedTo" label="分配给"></el-table-column>
      <el-table-column label="操作" width="200" align="right" header-align="center">
        <template slot-scope="scope">
          <el-button v-if="scope.row.status === '待处理'" type="text" @click="claimWorkOrder(scope.row)">认领工单</el-button>
          <el-button v-if="scope.row.status === '处理中'" type="text" @click="completeWorkOrder(scope.row)">完成工单</el-button>
          <el-button type="text" @click="viewWorkOrderDetails(scope.row)">查看详情</el-button>
          <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30, 40, 50]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      background
      style="text-align: right"
    ></el-pagination>

    <!-- 数据导入对话框 -->
    <DataImportDialog :visible.sync="importDialogVisible" @on-success="handleImportSuccess"/>

    <!-- 新增/编辑工单对话框 -->
    <WorkOrderForm
      :visible.sync="dialogVisible"
      :dialogTitle="dialogTitle"
      :formData="form"
      @submit="handleSubmit"
    />

    <!-- 工单详情对话框 -->
    <WorkOrderDetail
      :visible.sync="detailVisible"
      :formData="selectedRow"
    />
  </div>
</template>

<script>
import DataImportDialog from './components/DataImportDialog.vue';
import WorkOrderForm from './components/WorkOrderForm.vue';
import WorkOrderDetail from './components/WorkOrderDetail.vue';

export default {
  name: "DataCollection",
  components: { DataImportDialog, WorkOrderForm, WorkOrderDetail },
  data() {
    return {
      queryForm: {
        title: "",
        status: ''
      },
      totalTableData: [],
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      dialogTitle: "",
      form: {},
      selectedRows: [],
      loading: false,
      importDialogVisible: false,
      detailVisible: false,
      selectedRow: {}
    };
  },
  methods: {
    showImportDialog() {
      this.importDialogVisible = true;
    },
    handleImportSuccess(data) {
      // 处理导入成功的数据
      this.generateWorkOrders(data);
    },
    generateWorkOrders(importedData) {
      // 根据导入的数据生成工单并分配
      importedData.forEach(item => {
        const workOrder = {
          id: this.totalTableData.length ? this.totalTableData[this.totalTableData.length - 1].id + 1 : 1,
          title: item.title,
          status: '待处理',
          assignedTo: this.assignToSuitablePerson(item),
        };
        this.totalTableData.push(workOrder);
        this.tableData.push(workOrder);
      });
      this.fetchWorkOrders();
    },
    assignToSuitablePerson(item) {
      // 简单的分配逻辑，可以根据实际需求调整
      return '张三';
    },
    fetchWorkOrders() {
      this.loading = true;
      setTimeout(() => {
        const {title, status} = this.queryForm;
        const filteredData = this.totalTableData.filter(item => {
          return (
            (!title || item.title.includes(title)) &&
            (!status || item.status === status)
          );
        });
        this.total = filteredData.length;
        this.tableData = filteredData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
        this.loading = false;
      }, 1000);
    },
    resetData() {
      this.$refs.formRef.resetFields()
      this.fetchWorkOrders()
    },
    handleAdd() {
      this.dialogTitle = "新增工单";
      this.form = {};
      this.dialogVisible = true;
    },
    claimWorkOrder(workOrder) {
      // 确认认领
      this.$confirm('是否确认认领工单"' + workOrder.title + '"数据项?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 确认认领的逻辑
        workOrder.status = '处理中';
        workOrder.assignedTo = '当前用户'; // 假设当前用户是认领者
        this.updateWorkOrder(workOrder);
        this.$message({
          type: 'success',
          message: '认领成功!'
        });
      }).catch(() => {
        // 取消认领的逻辑
        this.$message({
          type: 'info',
          message: '已取消认领'
        });
      });
    },
    completeWorkOrder(workOrder) {
      // 确认完成
      this.$confirm('是否确认完成工单"' + workOrder.title + '"数据项?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 确认完成的逻辑
        workOrder.status = '已完成';
        workOrder.assignedTo = '当前用户'; // 假设当前用户是完成者
        this.updateWorkOrder(workOrder);
        this.$message({
          type: 'success',
          message: '完成成功!'
        });
      }).catch(() => {
        // 取消完成的逻辑
        this.$message({
          type: 'info',
          message: '已取消完成'
        });
      });
    },
    viewWorkOrderDetails(workOrder) {
      this.selectedRow = workOrder;
      this.detailVisible = true;
    },
    handleEdit(row) {
      this.dialogTitle = "编辑工单";
      this.form = {...row};
      this.dialogVisible = true;
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该工单信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const index = this.tableData.indexOf(row);
        if (index > -1) {
          this.tableData.splice(index, 1);
        }
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleBatchDelete() {
      if (this.selectedRows.length === 0) {
        this.$message({
          type: 'warning',
          message: '请选择要删除的工单信息!'
        });
        return;
      }
      this.$confirm('此操作将永久删除选中的工单信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.tableData = this.tableData.filter(row => !this.selectedRows.includes(row));
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleSelectionChange(selection) {
      this.selectedRows = selection;
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchWorkOrders();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchWorkOrders();
    },
    handleSubmit(formData) {
      if (this.dialogTitle === "新增工单") {
        formData.id = this.totalTableData.length ? this.totalTableData[this.totalTableData.length - 1].id + 1 : 1;
        this.totalTableData.unshift({...formData});
        this.tableData.unshift({...formData});
      } else {
        const index = this.tableData.findIndex(row => row.id === formData.id);
        if (index > -1) {
          this.$set(this.tableData, index, {...formData});
        }
      }
      this.dialogVisible = false;
    },
    updateWorkOrder(workOrder) {
      const index = this.tableData.findIndex(row => row.id === workOrder.id);
      if (index > -1) {
        this.$set(this.tableData, index, {...workOrder});
      }
    }
  },
  mounted() {
    // 页面加载时不自动获取数据，等待用户点击同步按钮
  }
};
</script>

<style scoped lang="scss">
.data-collection {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 20px;

  .el-row {
    margin-bottom: 20px;
  }

  .el-table {
    flex: 1;
    margin-bottom: 20px;
  }
}
</style>
